package cn.tedu.store.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.PhoneUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.tedu.store.common.ApiResult;
import cn.tedu.store.config.util.FileUtils;
import cn.tedu.store.entity.*;
import cn.tedu.store.entity.dto.AssgignDto;
import cn.tedu.store.entity.dto.PageDto;
import cn.tedu.store.mapper.EmployeeMapper;
import cn.tedu.store.service.IRepairService;
import cn.tedu.store.service.MeetingCheckRecodeDtoService;
import cn.tedu.store.temperatureDetection.entity.dto.EmployeeDto;
import cn.tedu.store.util.JsonResult;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 维修接单
 */
//@RestController只返回json数据
@Slf4j
@RestController
@RequestMapping(value = "/repair")
public class RepairController extends BaseController {

    //根据code获取微信小程序openid
    private static final String WECHAT_MP_GET_OPENID_URL = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";

    @Autowired
    IRepairService repairService;
//打电话
    @GetMapping("sendPhone")
    public void sendPhone(){

        repairService.morningClock();
    }
    //申请时通过电话号码和获取登录人科室和名
    @GetMapping(value = "/repairSelect")
    public Object repairSelect(String phone, String deptId) {
        List<Repair> repairs = repairService.repairSelect(phone, deptId);
        return new JsonResult<>(200, repairs);
    }

    //通过电话号码获取人员信息
    @GetMapping(value = "/selectEmployee")
    public Object selectEmployee(String phone) {
//        if (selectEmployee(phone) == null){
//            return new JsonResult<>(500, null);
//        }else {
        return new JsonResult<>(200, repairService.selectEmployee(phone));
//        }

    }


    //通过人员工号获取人员信息
    @GetMapping(value = "/selectEmployeeByCode")
    public Object selectEmployeeByCode(String employeeId) {
        return new JsonResult<>(200, repairService.selectEmployeeByCode(employeeId));
    }

    //接单
    @GetMapping(value = "/updateRepairState")
    public Object updateRepairState(String repairApplyId, String repairOperator, Date repairAcceptDate){
        Integer result = repairService.updateByRepairapplyid(repairApplyId,repairOperator,repairAcceptDate);
        if (result!=1){
            return new JsonResult<>(404);
        }else{
            return new JsonResult<>(200);
        }
    }

    //完成单子
    @GetMapping(value = "/updateAcceptState")
    public Object updateAcceptState(String repairApplyId, String repairOperator, Date repairFinishedDate){
        Integer result = repairService.updateAcceptState(repairApplyId,repairOperator,repairFinishedDate);
        if (result!=1){
            return new JsonResult<>(400,"没有找到数据");
        }else{
            return new JsonResult<>(200);
        }
    }

    //取消订单
    @GetMapping(value = "/cancelRepairOrder")
    public Object cancelRepairOrder(String repairApplyId, Date cancelDate){
        Integer result = repairService.cancelRepairOrder(repairApplyId,cancelDate);
        if (result!=1){
            return new JsonResult<>(404);
        }else{
            return new JsonResult<>(200);
        }
    }

    // 获取我的维修单,测试用
    @PostMapping(value = "/selectRepairOrder")
    public Object selectRepairOrder(@RequestBody List<Integer> repairState){
        return new JsonResult<>(200,repairService.selectRepairOrder(repairState));
    }

    //获取所有没有完成的维修单
    @GetMapping(value = "/selectAllRepairOrder")
    public Object selectAllRepairOrder(String repairApplyOperator,String stateOne,String stateTwo,String repairStateOne,String repairStateTwo){
//        String s="";
//        String[] split = repairState.split(",");
//        for (int i = 0; i < transfersplit.length; i++) {
//            s+="'"+split[i]+"',";
//        }
//        s="("+s.substring(0,s.length()-1)+")";

            List<RepariOrder> repariOrders = repairService.selectAllRepairOrder(repairApplyOperator, stateOne, stateTwo, repairStateOne, repairStateTwo);


        if (repariOrders.isEmpty()) {
            return new JsonResult<>(400, "没有查到数据");
        }else {
            return new JsonResult<>(200,repariOrders);
        }
    }



    @GetMapping(value = "/selectAllRepairOrder2")
    public Object selectAllRepairOrder2(String repairApplyOperator,String stateOne,String stateTwo,String repairStateOne,String repairStateTwo){

        List<RepariOrder> repariOrders = repairService.selectAllRepairOrder(repairApplyOperator, stateOne, stateTwo, repairStateOne, repairStateTwo);


        if (repariOrders.isEmpty()) {
            return new JsonResult<>(400, "没有查到数据");
        }else {
            return new JsonResult<>(200,repariOrders);
        }
    }

    @GetMapping(value = "/selectAllRepairOrder4")
    public Object selectAllRepairOrder4(String repairApplyOperator,String stateOne,String stateTwo,String repairStateOne,String repairStateTwo){
//        String s="";
//        String[] split = repairState.split(",");
//        for (int i = 0; i < split.length; i++) {
//            s+="'"+split[i]+"',";
//        }
//        s="("+s.substring(0,s.length()-1)+")";

        List<RepariOrder> repariOrders = repairService.selectAllRepairOrder3(repairApplyOperator, stateOne, stateTwo, repairStateOne, repairStateTwo);


        if (repariOrders.isEmpty()) {
            return new JsonResult<>(400, "没有查到数据");
        }else {
            return new JsonResult<>(200,repariOrders);
        }
    }
    @GetMapping(value = "/selectAllRepairOrder3")
    public Object selectAllRepairOrder3(String repairApplyOperator,String stateOne,String stateTwo,String repairStateOne,String repairStateTwo){
//        String s="";
//        String[] split = repairState.split(",");
//        for (int i = 0; i < split.length; i++) {
//            s+="'"+split[i]+"',";
//        }
//        s="("+s.substring(0,s.length()-1)+")";

        List<RepariOrder> repariOrders = repairService.selectAllRepairOrder3(repairApplyOperator, stateOne, stateTwo, repairStateOne, repairStateTwo);


        if (repariOrders.isEmpty()) {
            return new JsonResult<>(400, "没有查到数据");
        }else {
            return new JsonResult<>(200,repariOrders);
        }
    }

    @GetMapping(value = "/selectAllRepairOrderEnd")
    public Object selectAllRepairOrderEnd(String repairApplyOperator,String stateOne,String stateTwo,String repairStateOne,String repairStateTwo){
//        String s="";
//        String[] split = repairState.split(",");
//        for (int i = 0; i < split.length; i++) {
//            s+="'"+split[i]+"',";
//        }
//        s="("+s.substring(0,s.length()-1)+")";

        List<RepariOrder> repariOrders = repairService.selectAllRepairOrderEnd(repairApplyOperator, stateOne, stateTwo, repairStateOne, repairStateTwo);


        if (repariOrders.isEmpty()) {
            return new JsonResult<>(400, "没有查到数据");
        }else {
            return new JsonResult<>(200,repariOrders);
        }
    }
    @PostMapping(value = "/repairInsert")
    public JsonResult repairInsert(@RequestBody(required = false) Repair repair) {
        String s = repairService.repairApply(repair);

        //自动派单
        return new JsonResult<>(200, s);
    }

    @GetMapping(value = "/selectDept")
    public Object selectDept() {
        return new JsonResult<>(200, repairService.selectDepartment());
    }

    //加上领导  领导科室  状态
    @GetMapping(value = "/selectMyRepairOrderById")
    public Object selectMyRepairOrderById(String repairApplyId,String repairState){
        Repair repair = repairService.selectMyRepairOrderById(repairApplyId,repairState);
        if (repair==null){
            return new JsonResult<>(404,"没有找到申请的单号");
        }else {
            return new JsonResult<>(200,repair);
        }
    }
    //获取科室
    @GetMapping("dept")
    public String dept(String repairLeadership){
    String dept =    repairService.getdept(repairLeadership);
        return dept;
    }

    //会议签到20211005
    @GetMapping(value = "/meetingCheckRecode")
    public JsonResult meetingCheckRecode(@RequestBody(required = false) MeetingCheckRecode meetingCheckRecode) {
        repairService.meetingRecode(meetingCheckRecode);
        return new JsonResult<>(200, null);
    }

    //根据工号查询个人会议20211008
    @GetMapping(value = "/meetingSelect")
    public Object meetingSelect(String empCode,String meetingCode) {
        List<MeetingCheckRecode> meetingCheckRecodes = repairService.meetingSelect(empCode,meetingCode);
        Date meetingBeginDate = meetingCheckRecodes.get(0).getMeetingBeginDate();
        System.out.println(meetingBeginDate);
        //meetingCheckRecodes.get(0).setMeetingBeginDate(meetingBeginDate.getTime());
        return new JsonResult<>(200, meetingCheckRecodes);
    }

    //
    //根据会议号查询个人会议20211011
    @GetMapping(value = "/meetingSelectById")
    public Object meetingSelectById(String meetingCode) {
        List<MeetingCheckRecode> meetingCheckRecodes = repairService.meetingSelectById(meetingCode);
        if (meetingCheckRecodes.size()>0)
        {
            return new JsonResult<>(200, meetingCheckRecodes);
        }else {
            return new JsonResult<>(400, "没有查到数据");
        }

    }

    //存在人员的会议签到20211009
    @GetMapping(value = "/updateMeetingRecode")

    public Object updateMeetingRecode(Date empBeginDate,String empCode, String meetingCode){
        Integer result = repairService.updateMeetingRecode(empBeginDate,empCode, meetingCode);
        if (result==1){
            return new JsonResult<>(200,"应参会人员签到成功");
        }else if(result==2){
            return new JsonResult<>(201,"参会替换人员签到成功");
        }else {
            return new JsonResult<>(202,"签到失败");
        }
    }

    //发言、请假、替换20211011
    @GetMapping(value = "/updatePersonRecode")
    public Object updatePersonRecode(String reportState, String leaveState, String replaceState, String empCode, String meetingCode){
        Integer result = repairService.updatePersonRecode(reportState,leaveState, replaceState,empCode,meetingCode);
        if (result==1){
            return new JsonResult<>(200,"成功");
        }else {
            return new JsonResult<>(203,"失败");
        }
    }

    @GetMapping(value = "/selectDutyTable")
    public Object selectDutyTable(){
        return  new JsonResult<>(200,repairService.selectXxkPaiban());
    }
    @GetMapping(value = "/selectDutyTable1")
    public Object selectDutyTable1(){
        return  new JsonResult<>(200,repairService.selectXxkPaiban1());
    }



    @GetMapping(value = "/selectDutyTable2")
    public Object selectDutyTable2(){
        return  new JsonResult<>(200,repairService.selectEm());
    }

    /**
     *
     * @param binder
     * @param request
     */



    @InitBinder
    public void initBinder(WebDataBinder binder, WebRequest request) {
        //转换日期 注意这里的转化要和传进来的字符串的格式一直 如2015-9-9 就应该为yyyy-MM-dd
        DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));// CustomDateEditor为自定义日期编辑器
    }
    @PostMapping("/getPhone")
    @Transactional
    public Object Phone(@RequestBody MpDto dto) {
        Object r = getPhone(dto);
        return new JsonResult<>(200, r);
    }
    public Object getPhone(@RequestBody MpDto dto) {
        JSONObject object = null;
        try {
            String url = String.format(WECHAT_MP_GET_OPENID_URL, "wxbe061859f1488b2c", "9fb219fca221c7f51eedc6d7f1dad9d4", dto.getCode());
            //log.info("request accessToken from url: {}", url);
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);
            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            String tokens = EntityUtils.toString(httpEntity, "utf-8");
            object = JSONUtil.parseObj(tokens);
            //log.info("request accessToken success. [result={}]", object);
            if (!object.keySet().contains("openid")) {
                throw new RuntimeException("未能获得openid");
            }
            String session_key = object.get("session_key").toString().replaceAll("\"", "");
            //解密，返回解析的json字符串
            String decryData = getPhoneNumberBeanS5(dto.getEncryptedData(), session_key, dto.getIv());
            if (decryData == null) {
                throw new RuntimeException("数据异常：" + decryData);
            }
            // json字符串格式:{"phoneNumber":"18608608556","purePhoneNumber":"18608608556","countryCode":"86","watermark":{"timestamp":1615428996,"appid":"wx41a933510fdcf838"}}
            // 通过json解析工具列，将json字符串解析成json对象
            JSONObject phoneObj = JSONUtil.parseObj(decryData);
            // 从json对象中通过key获取对应的值（phoneNumber = 18888888888）
            String phoneNumber = phoneObj.getStr("phoneNumber");
            // 验证手机号
            boolean phone = PhoneUtil.isPhone(phoneNumber);
            if (!phone) {
                throw new RuntimeException("手机号码错误");
            }

            // 查询不到数据返回
            return new JsonResult<>(200, phone);
        } catch (Exception ex) {
            throw new RuntimeException("fail to request wechat access token. [error={}]", ex);
        }
    }

    // 获得微信小程序手机号和tk
    @PostMapping("/getWechatMpPhoneAndTk")
    @Transactional
    public Object getWechatMpPhoneAndTk(@RequestBody MpDto dto) {
        Object r = getWechatMpPhone(dto);
        return new JsonResult<>(200, r);
    }



    public Object getWechatMpPhone(@RequestBody MpDto dto) {
        JSONObject object = null;
        try {
            String url = String.format(WECHAT_MP_GET_OPENID_URL, "wxbe061859f1488b2c", "9fb219fca221c7f51eedc6d7f1dad9d4", dto.getCode());
            log.info("request accessToken from url: {}", url);
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);
            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            String tokens = EntityUtils.toString(httpEntity, "utf-8");
            object = JSONUtil.parseObj(tokens);
            log.info("request accessToken success. [result={}]", object);
            if (!object.keySet().contains("openid")) {
                throw new RuntimeException("未能获得openid");
            }
            String session_key = object.get("session_key").toString().replaceAll("\"", "");
            //解密，返回解析的json字符串
            String decryData = getPhoneNumberBeanS5(dto.getEncryptedData(), session_key, dto.getIv());
            if (decryData == null) {
                throw new RuntimeException("数据异常：" + decryData);
            }
            // json字符串格式:{"phoneNumber":"18608608556","purePhoneNumber":"18608608556","countryCode":"86","watermark":{"timestamp":1615428996,"appid":"wx41a933510fdcf838"}}
            // 通过json解析工具列，将json字符串解析成json对象
            JSONObject phoneObj = JSONUtil.parseObj(decryData);
            // 从json对象中通过key获取对应的值（phoneNumber = 18888888888）
            String phoneNumber = phoneObj.getStr("phoneNumber");
            // 验证手机号
            boolean phone = PhoneUtil.isPhone(phoneNumber);
            if (!phone) {
                throw new RuntimeException("手机号码错误");
            }
            // 通过手机号查询人员信息
            List<Employee> employees = repairService.selectEmployee(phoneNumber);
            if (CollUtil.isNotEmpty(employees)) {
                // 查询到信息，从这里返回数据结束，不会走下面
                //return new JsonResult<>(200, employees.get(0));
                return employees.get(0);
            }
            // 查询不到数据返回
            return new JsonResult<>(500, null);
        } catch (Exception ex) {
            throw new RuntimeException("fail to request wechat access token. [error={}]", ex);
        }
    }

    public String getPhoneNumberBeanS5(String decryptData, String key, String iv) throws Exception {
        /*
         *这里你没必要非按照我的方式写，下面打代码主要是在一个自己的类中 放上decrypts5这个解密工具，工具在下方有代码
         */
        // 这里解析成了一个JSON的字符串
        String resultMessage = decryptS5(decryptData, "UTF-8", key, iv);
        return resultMessage;
    }

    /**
     * 解密工具直接放进去即可
     */
    public static String decryptS5(String sSrc, String encodingFormat, String sKey, String ivParameter) throws Exception {
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] raw = decoder.decodeBuffer(sKey);
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            IvParameterSpec iv = new IvParameterSpec(decoder.decodeBuffer(ivParameter));
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            byte[] myendicod = decoder.decodeBuffer(sSrc);
            byte[] original = cipher.doFinal(myendicod);
            String originalString = new String(original, encodingFormat);
            return originalString;
        } catch (Exception ex) {
            return null;
        }
    }


    /**
     * fan
     * 维修评价
     */
    @GetMapping("maintenanceAppraise")
    public  JsonResult maintenanceAppraise(String repairApplyId,String suggestion,String repairEvaluate){

        repairService.byRepairApplyIdSuggestion(repairApplyId,suggestion,repairEvaluate);
        //通过申请人员号进行评价
        return new JsonResult(200);
    }

    /**
    * 评价查询
    */
    @GetMapping("selectAppraise")
    public  JsonResult  selectAppraise(String repairApplyId){
        Repair repair = repairService.selectMyRepairOrderById(repairApplyId, "3");
        return new JsonResult(200,repair);
    }
    /**
     * 请假休息
     */
    @GetMapping("lockout")
    public JsonResult lockout(String emplCode){

        repairService.lockout(emplCode);
        return new JsonResult(200);
    }

    @Autowired
    EmployeeMapper employeeMapper;



    /**
     * 派单
     */
    @GetMapping("dispatch")
    public JsonResult dispatch(String emplCode , String emplName ,String  repairApplyId){

        repairService.dispatch(emplCode,emplName,repairApplyId);


        return new JsonResult(200);
    }
    @Autowired
    MeetingCheckRecodeDtoService meetingCheckRecodeDtoService;
//    //员工搜索接口
    @GetMapping("getList")
    public JsonResult getList(){
        List<String> names =   meetingCheckRecodeDtoService.getList();
        return new JsonResult(200,names);
    }
    /**
     * 评价
     */
    @GetMapping("appraise")
    public JsonResult appraise(String emplCode ,String  repairApplyId,String repairEvaluate,String suggestion){

        Repair repair = repairService.selectMyRepairOrderById(repairApplyId, "3");

                if(Objects.isNull(repair)){
                    throw new RuntimeException("当前订单不存在");
                }
                if (StringUtils.isBlank(repair.getRepairEvaluate())||StringUtils.isBlank(repair.getSuggestion())){
                    repairService.appraise(emplCode,repairApplyId,repairEvaluate,suggestion);
                }else {
                    throw new RuntimeException("已评价不能重复评价");
                }


        return new JsonResult(200);
    }

    /**
     * 进度填写
     */
    @GetMapping("progress")
    public JsonResult progress(String repairApplyId ,String progress){
        Repair repair = repairService.progress(repairApplyId,progress);

        return new JsonResult(200,repair);
    }
    /**
     * 维修进度查询
     */
    @GetMapping("getProgress")
    public JsonResult getProgress(String repairApplyId){
        List<Progress> progress  = repairService.selcetProgress(repairApplyId);
        return  new JsonResult(200,progress);
    }

    /**
     * 接单二维码
     */

    /**
     * 我的接单
     */
    @GetMapping("getWeRepair")
    public JsonResult getWeRepair(String repairApplyOperator){
         List<Repair> repairs = repairService.getWeRepair(repairApplyOperator);
        return  new JsonResult(200,repairs);
    }
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 自動接單
     */
    @GetMapping("automaticOrderTaking")
    public  JsonResult   automaticOrderTaking(){
        Date start = new Date();start.setHours(0);start.setMinutes(0); start.setSeconds(0);
        Date end = new Date();end.setHours(23);end.setMinutes(59); end.setSeconds(59);
        SimpleDateFormat toDay = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<Repair> repairs  = repairService.selectByToDateRepairAll(sdf.format(start),sdf.format(end));
//
        repairs.forEach(s->stringRedisTemplate.opsForList().leftPush("weixiu",JSONUtil.toJsonPrettyStr(s)));
        repairService.automaticDispatch(repairs,sdf.format(start),sdf.format(end));

        return new JsonResult(200);
    }
    /**
     * 查询详细
     */
    @GetMapping("getRepair")
    public JsonResult getRepair(String repairApplyId){
         Repair repair =  repairService.selectRepairById(repairApplyId);
        return new JsonResult(200,repair);
    }


    /**
     * 上传图片
     */
    @PostMapping("uploadImg")
    public void uploadImg(@RequestBody MultipartFile file, String repairApplyId) throws IOException {

        repairService.uploadImg(file,repairApplyId);
    }

    /**
     * 预览
     */
    @GetMapping("imgPreview")
    public JsonResult imgPreview( String repairApplyId) throws FileNotFoundException {
        String s  = repairService.imgPreview(repairApplyId);
        return new JsonResult(200,s);
    }


    //催单
    @GetMapping("reminders")
    public ApiResult reminders(String repairApplyId){
        //查询订单
        Repair repair1 = repairService.selectRepairById(repairApplyId);

        if (!StringUtils.isBlank(repair1.getRepairApplyState())){
            throw new RuntimeException("已进行催单,请耐心等待");
        }else {
            //催单
            repair1.setRepairApplyState("1");
            repairService.reminders(repair1);
            //发信息

            return ApiResult.ok();
        }

    }
    //投诉
    @GetMapping("complaints")
    public ApiResult complaints(String repairApplyId,String message){
        Repair repair1 = repairService.selectRepairById(repairApplyId);
        if (!Objects.isNull(repair1.getRepairApplyComplaints())){
            throw new RuntimeException("已投诉不能进行二次投诉");

        }
        if (repair1.getRepairState().equals("2") || repair1.getRepairState().equals("3")){
             repairService.updateComplaintsByRepairapplyid(repairApplyId,message);
        }else {
            throw new RuntimeException("未被接单不能投诉");
        }




        return ApiResult.ok();
    }
    //撤回
    @GetMapping("withdraw")
    public ApiResult withdraw(String repairApplyId){
        //
        Repair repair1 = repairService.selectRepairById(repairApplyId);
        if (!Objects.isNull(repair1.getRepairApplyComplaints())){
            throw new RuntimeException("已投诉不可撤回");

        }

    if (repair1.getRepairState().equals("2")||repair1.getRepairState().equals("1")){
         repair1.setRepairState("5");
        repairService.updateRepairStateByRepairApplyId(repairApplyId,repair1.getRepairState(),new Date());
        }else {
        throw new RuntimeException("此订单不可撤回");
    }


        return ApiResult.ok();
    }


    //投诉信息
    @GetMapping("selectComplaints")
    public ApiResult selectComplaints(String repairApplyId){
        Repair repair1 = repairService.selectRepairById(repairApplyId);
        return ApiResult.ok(repair1);
    }
    //模糊查询
    @GetMapping("selectLeadershipDept")
    public ApiResult selectLeadershipDept(String emplCode){
        EmployeeDto deptCode =   repairService.getbyEmplCode(emplCode);
            return ApiResult.ok(deptCode);
    }
    //申请人结束时间修改
    @GetMapping("updataEndTime")
    public ApiResult updataEndTime(String repairApplyId,String endTime){

        Date parse = DateTime.of(endTime, "yyyy-MM-dd HH:mm:ss");
        System.out.println(parse);
        repairService.updataEndTime(repairApplyId,parse);
        return ApiResult.ok();
    }
    //维修人结束时间修改
    @GetMapping("upadtaEndTime2")
    public ApiResult  upadtaEndTime2(String repairApplyId,String endTime){
        Date parse = DateTime.of(endTime, "yyyy-MM-dd HH:mm:ss");
        System.out.println(parse);
        repairService.upadtaEndTime2(repairApplyId,parse);
        return ApiResult.ok();
    }

    //录音上传
    @PostMapping("uploadRecording")
    public void uploadRecording(@RequestBody MultipartFile file,String repairApplyId,String repairNum,String  emplCode) throws IOException {
        repairService.uploadRecording(file,repairApplyId,repairNum,emplCode);
    }

    //查询
    @GetMapping("getRecording")
    public String getRecording(String  repairApplyId, HttpServletResponse response) throws FileNotFoundException {
     Recording recording =    repairService.getRecording(repairApplyId);



        // path是指欲下载的文件的路径。
        File file = new File(recording.getRepairRecording());
        // 取得文件名。
        String filename = file.getName();
        // 取得文件的后缀名。
        String ext = filename.substring(".".lastIndexOf(filename) + 1).toUpperCase();

        FileInputStream stream = new FileInputStream(recording.getRepairRecording());

        String image  = Base64.encode(stream);
        return image;

    }
    //下载
    @GetMapping("dow")
    public void dow(String  repairApplyId, HttpServletResponse response){

        Recording recording =    repairService.getRecording(repairApplyId);
        FileUtils.download(recording.getRepairRecording(),response);
    }
    //转单
    @GetMapping("transfer")
    public ApiResult transfer(String repairApplyId,String  emplCode){
        repairService.transfer(repairApplyId,emplCode);
        return ApiResult.ok();
    }

    //转派记录
    @GetMapping("secletAllTransfer")
    public ApiResult secletAllTransfer(){
    List<Transfer> transfers =       repairService.secletAllTransfer();
    return ApiResult.ok(transfers);
    }

    @GetMapping("allOutcome")
    public ApiResult allOutcome(){
            List<Repair> repairs     = repairService.allOutcome();
        return ApiResult.ok(repairs);
    }

    //查看科室
    @GetMapping("deptAllRepair")
    public ApiResult deptAllRepair(String stateOne,String stateTwo,String repairStateOne,String repairStateTwo,String employeeDept){
        List<RepariOrder> repariOrders = repairService.deptAllRepair( stateOne, stateTwo, repairStateOne, repairStateTwo,employeeDept);
        if(repairStateOne.equals("1")||repairStateOne.equals("2")){
            System.out.println("1111");
            List<RepariOrder> collect = repariOrders.stream().filter(s -> s.getRepairAcceptDate() != null).sorted(Comparator.comparing(RepariOrder::getRepairAcceptDate)).collect(Collectors.toList());
            return ApiResult.ok(collect);
        }else if (repairStateOne.equals("3")){
            System.out.println("走");
            List<RepariOrder> collect = repariOrders.stream().filter(s -> s.getRepairEndDate() != null).sorted(Comparator.comparing(RepariOrder::getRepairEndDate).reversed()).collect(Collectors.toList());

            return ApiResult.ok(collect);

        }


//
        return ApiResult.ok(repariOrders);
    }
    //相关人员表
    @GetMapping("relevantPersonnel")
    public ApiResult relevantPersonnel(String emplCode){
        List<RepariOrder> repariOrders   =  repairService.relevantPersonnel(emplCode);
        return ApiResult.ok(repariOrders);
    }

    @GetMapping("get")
    public void tset(){
        repairService.send();
    }

    @GetMapping("updateFinishedDate")
    public ApiResult updateFinishedDate(String  repairApplyId,Integer  time){
        repairService.updateFinishedDate(repairApplyId,time);
        return ApiResult.ok();
    }


    @GetMapping("updateApplyEndDate")
    public ApiResult updateApplyEndDate(String  repairApplyId,Integer  time ){
        repairService.updateApplyEndDate(repairApplyId,time);
        return ApiResult.ok();
    }


    @GetMapping("allRepair")
    public ApiResult allRepair(String  endTime,String startTime,String repairState){

         List<Repair> repairs=repairService.allRepair(endTime,startTime,repairState);
        return ApiResult.ok(repairs);
    }



    //查询询记录
    @GetMapping("/assignAll")
    public ApiResult assignAll(String  endTime,String startTime,String repairState){
          List<Assign> assignAll  = repairService.assignAll(endTime,startTime,repairState);
        int size = assignAll.size();
        AssgignDto assgignDto = new AssgignDto();
        assgignDto.setAssigns(assignAll);
        assgignDto.setAssignsSize(size);
        return ApiResult.ok(assignAll);
    }
    //
    @GetMapping("sendOfficialAccount")
    public ApiResult sendOfficialAccount(String dept,String  data){
        repairService.sendOfficialAccount(dept,data);
    return ApiResult.ok();
    }

    //流程分页查询
    @GetMapping("workFlowList")
    public ApiResult  workFlowList(int page,int pageSize){

        PageDto<WorkFlow> workFlow = repairService.workFlowList(page, pageSize);

        return ApiResult.ok(workFlow);
    }


    //耗材查询
    @GetMapping("querySupplies")
    public ApiResult   querySupplies(String supplies){
                String    q ="%"+supplies+"%";
        List<Supplies> suppliess       = repairService.querySupplies(q);
        return ApiResult.ok(suppliess);
    }

    //耗材添加
    @PostMapping("addSupplies")
    public ApiResult addSupplies(@RequestBody List<Supplies> supplies,String repairApplyId){
        repairService.addSupplies(supplies,repairApplyId);
        return ApiResult.ok();
    }

    //查询相关订单耗材
    @GetMapping("relevancyOrders")
    public ApiResult relevancyOrders(String repairApplyId){
        log.info("查询");
        List<Supplies> supplies=  repairService.relevancyOrders(repairApplyId);
        return ApiResult.ok(supplies);
    }

    /**
     * 删除耗材
     * @param repairApplyId
     * @param itemCode
     * @return
     */
    @GetMapping("deleteSupplies")
    public ApiResult deleteSupplies(String repairApplyId,String itemCode){
        repairService.deleteSupplies(repairApplyId,itemCode);
        return ApiResult.ok();
    }

    /**
     * 
     */


}
